package com.pulook.daikuan.controller;

import java.util.List;

import javax.inject.Inject;

import org.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.pulook.daikuan.dao.YonghuMapper;
import com.pulook.daikuan.dao.SessionUtil;
import com.pulook.daikuan.model.Yonghu;

@Controller
public class Denglu0 {

	@Inject
	YonghuMapper y;
	public Yonghu y1;
	/**
	 * 登录也
	 */
	@RequestMapping("/denglu")
	public String de(){
		return "denglu";
	}
	
	/**
	 * 用户登录
	 * @param m
	 * @param yonghuming
	 * @param mima
	 * @return
	 */
	@RequestMapping(value="/ydenglu", produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String dl(Model m , String yonghuming, String mima){
	
		Yonghu y2 = new Yonghu();
		y2.setYonghuming(yonghuming);
		int num = y.getByConditionForNum(y2);
		y2.setStart(0);
		y2.setEnd(num);
		List<Yonghu> desc = y.getYonghuByConditionDesc(y2);

		String f = "";
		String quanxian0 = "";
		if (desc.size() == 0) {
			f = "帐号不存在！";
//			quanxian0 = "错误";
		}else if(desc.get(0).getYonghuming().equals(yonghuming) && desc.get(0).getMima().equals(mima)){
			
			f = "正确";
			quanxian0 = desc.get(0).getQuanxian();
			SessionUtil.setAttributeForSession("yonghuming", yonghuming);
			SessionUtil.setAttributeForSession("quanxian", desc.get(0).getQuanxian());
			SessionUtil.setAttributeForSession("xingming", desc.get(0).getXingming());
			}else{
				f = "密码不正确";
			}
		
		JSONObject j = new JSONObject();
		try {
			j.accumulate("f", f);
			j.accumulate("q", quanxian0);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return j.toString();
	}
	
	
	/***
	 * 注册页
	 */
	@RequestMapping("zhuceye")
	public String zcy(){
		return "zhuceye";
	}
	/**
	 * 注册
	 */
	@RequestMapping(value="/zhuce", produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String zc(String yonghuming, String mima, String xingming){
		
		Yonghu y0 = new Yonghu();
		y0.setYonghuming(yonghuming);
		int num = y.getByConditionForNum(y0);
		y0.setStart(0);
		y0.setEnd(num);
		List<Yonghu> desc = y.getYonghuByConditionDesc(y0);
//		System.out.println("sss"+desc.size());
		String f = "";
		
		if (desc.size() > 0) {
			f = "改帐号已存在";
		}else{
			Yonghu y01 = new Yonghu();
			y01.setYonghuming(yonghuming);
			y01.setMima(mima);
			y01.setXingming(xingming);
			y01.setQuanxian("用户");
			y.insert(y01);
			f = "注册成功";
		}
		
		JSONObject j = new JSONObject();
		try {
			j.accumulate("f", f);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return j.toString();
	}
	
	@RequestMapping("/tuichu")
	public String tc(){
		
		SessionUtil.delSession();
		return "forward:denglu";
	}
}
